package com.lyh.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;

/**
 * redis工具类
 */
@Component
public class JedisPoolUtils {

    @Autowired
    private JedisPool jedisPool;

    private int maxTotal = 10;
    private int maxIdle = 50;
    private String host = "localhost";
    private int port = 6379;

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Bean
    public JedisPool jedisPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(this.maxTotal);
        config.setMaxIdle(this.maxIdle);

        //初始化成员属性 jedispool
        return new JedisPool(config, this.host, this.port);
    }

    //获取连接
    //@Bean
    private Jedis getJedis(){
        return this.jedisPool.getResource();
    }

    /**
     * 给数据库添加限时的键值对
     * @param key 键
     * @param value 值
     * @param time 时间
     * @return 添加状态
     */
    public String setLimitTimeValue(String key, String value, int time){
        Jedis jedis = this.getJedis();
        String status = jedis.setex(key,time,value);
        jedis.close();
        return status;
    }

    public String setValue(String key,String value){
        Jedis jedis = this.getJedis();
        String result = jedis.set(key, value);
        jedis.close();
        return result;
    }

    public String getValue(String key){
        Jedis jedis = this.getJedis();
        String result = jedis.get(key);
        jedis.close();
        return result;
    }

    public double removeValue(String username) {
        Jedis jedis = this.getJedis();
        return jedis.del(username);
    }
}

